package queue;

import link.LinkedList;

/**
 * 使用链表来实现队列操作
 * Created by zhaoxin on 2018/7/22.
 */
public class LinkedListQueue<E> implements Queue {


    private class Node<E>{
        E e;
        Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e, null);
        }
        public Node(){
            this(null, null);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "e=" + e +
                    ", next=" + next +
                    '}';
        }
    }

    private Node head;
    private Node tail;
    private int size;

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public void enqueue(Object o) {
        E e = (E) o;
        if (tail == null){
            tail = new Node(e);
            head = tail;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public Object dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("队列为空，不能出队元素！");
        Node deletedNode = head;
        head = head.next;
        deletedNode.next = null;
        // 处理队列链表中的元素只有一个的情况，避免tail依旧指向和head共同指向的那个被删除的元素
        if (head == null){
            tail = null;
        }
        size --;
        return deletedNode.e;
    }

    @Override
    public Object getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列不能为空！");
        }
        return head.e;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int getSize() {
        return size;
    }


    public static void main(String[] args) {

        LinkedListQueue linkedListQueue = new LinkedListQueue();
        for (int i = 0; i < 10; i++) {
            linkedListQueue.enqueue(i);
            System.out.println(linkedListQueue);
            if (i % 3 == 2){
                linkedListQueue.dequeue();
            }

        }

        System.out.println(linkedListQueue);
    }

}
